//////////////////////////////////////////////////////////////////////////////////
//	Copyright 2011 by Yosef Grabivker, ryuho@homenetworksoft.com
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//////////////////////////////////////////////////////////////////////////////////

#include <wx/wx.h>
#include <wx/thread.h>
#include "commandqueue.h"

CCommandQueue::CCommandQueue()
{
}

CCommandQueue::~CCommandQueue()
{
}

void CCommandQueue::AddRequest(const COMMANDREQUEST& cmd, bool bHead)
{
	wxCriticalSectionLocker locker(m_csInGuard);

	//erase queue if quit
	if (  cCmdQuit == cmd.code )
	{
		while( !m_qIn.empty() ) m_qIn.pop();
	}

	if ( m_qIn.size() > QUEUE_MAX_SIZE )
	{
		m_qIn.pop();
	}

	if ( bHead )
	{
		COMMANDREQUEST cmdTmp;
		REQUESTQUEUE	qIN;
		qIN.push(cmd);

		while( !m_qIn.empty() )
		{
			cmdTmp = m_qIn.front();
			qIN.push(cmdTmp);
			m_qIn.pop();
		}

		m_qIn=qIN;
	}
	else
	{
		m_qIn.push( cmd );
	}
}

void CCommandQueue::AddResponce(const COMMANDRESPONSE& cmd)
{
	wxCriticalSectionLocker locker(m_csOutGuard);

	if ( m_qOut.size() > QUEUE_MAX_SIZE )
	{
		while( !m_qOut.empty() ) m_qOut.pop();
	}


	m_qOut.push( cmd );
}

bool CCommandQueue::GetRequest(COMMANDREQUEST& cmd)
{
	bool bRes(false);
	
	wxCriticalSectionLocker locker(m_csInGuard);
	
	if ( !m_qIn.empty() )
	{
		cmd = m_qIn.front();
		m_qIn.pop();
		bRes = true;
	}
	
	return bRes;
}

bool CCommandQueue::GetResponce(COMMANDRESPONSE& cmd)
{
	bool bRes(false);
	
	wxCriticalSectionLocker locker(m_csOutGuard);
	
	if ( !m_qOut.empty() )
	{
		cmd = m_qOut.front();
		m_qOut.pop();
		bRes = true;
	}
	
	return bRes;
}
